/**
 *====================================================
 * 文件名称: FinanceBaseAction.java
 * 修订记录：
 * No    日期				作者(操作:具体内容)
 * 1.    2015年10月24日			chenxy(创建:创建文件)
 *====================================================
 * 类描述：(说明未实现或其它不应生成javadoc的内容)
 */
package com.yuexunit.finance.context;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.yuexunit.core.BusinessException;
import com.yuexunit.finance.bulkstock.entity.BulkstockInfoEntity;
import com.yuexunit.finance.bulkstock.service.BulkstockInfoService;
import com.yuexunit.finance.common.util.DateUtils;
import com.yuexunit.finance.common.util.LongUtils;
import com.yuexunit.finance.member.service.EnterpriseService;
import com.yuexunit.finance.project.AuthenticatEntity;
import com.yuexunit.finance.project.action.v1.dto.FinanceProcessCastor;
import com.yuexunit.finance.project.action.v1.model.InterestContainer;
import com.yuexunit.finance.project.action.v1.model.InterestContainerBulkstock;
import com.yuexunit.finance.project.action.v1.model.InterestEstimate;
import com.yuexunit.finance.project.entity.ContainerBulkstockEntity;
import com.yuexunit.finance.project.entity.ContainerInventoryEntity;
import com.yuexunit.finance.project.entity.FinanceApplicationEntity;
import com.yuexunit.finance.project.entity.FinanceBulkstockEntity;
import com.yuexunit.finance.project.entity.FinanceContainerEntity;
import com.yuexunit.finance.project.entity.FinanceContainerLogEntity;
import com.yuexunit.finance.project.entity.FinanceCreditEntity;
import com.yuexunit.finance.project.entity.FinanceCreditReplenishContainerEntity;
import com.yuexunit.finance.project.entity.FinanceProcessEntity;
import com.yuexunit.finance.project.entity.FinanceProductExpenseEntity;
import com.yuexunit.finance.project.entity.LoanNoticeEntity;
import com.yuexunit.finance.project.entity.PickupApplicationEntity;
import com.yuexunit.finance.project.entity.SupervisionConfirmationEntity;
import com.yuexunit.finance.project.entity.lexicon.ApplicationStateEnum;
import com.yuexunit.finance.project.entity.lexicon.AuthenticatStateEnum;
import com.yuexunit.finance.project.entity.lexicon.BillingMethodEnum;
import com.yuexunit.finance.project.entity.lexicon.BulkstockSourceEnum;
import com.yuexunit.finance.project.entity.lexicon.ExpenseMethodEnum;
import com.yuexunit.finance.project.entity.lexicon.ExpenseScopeEnum;
import com.yuexunit.finance.project.entity.lexicon.ExpenseTypeEnum;
import com.yuexunit.finance.project.entity.lexicon.FinanceStateEnum;
import com.yuexunit.finance.project.entity.lexicon.LoanMethodEnum;
import com.yuexunit.finance.project.entity.lexicon.ProductTypeEnum;
import com.yuexunit.finance.project.entity.lexicon.ReplenishStateEnum;
import com.yuexunit.finance.project.entity.lexicon.SupervisionStateEnum;
import com.yuexunit.finance.project.service.AbnormalRiskService;
import com.yuexunit.finance.project.service.BadassetsHandleService;
import com.yuexunit.finance.project.service.BadassetsInventoryService;
import com.yuexunit.finance.project.service.BailReturnService;
import com.yuexunit.finance.project.service.ContainerBulkstockHistoryService;
import com.yuexunit.finance.project.service.ContainerBulkstockService;
import com.yuexunit.finance.project.service.ContainerInventoryHistoryService;
import com.yuexunit.finance.project.service.ContainerInventoryRelieveService;
import com.yuexunit.finance.project.service.ContainerInventoryService;
import com.yuexunit.finance.project.service.ContainerInventorySignService;
import com.yuexunit.finance.project.service.ContainerInventoryTallyService;
import com.yuexunit.finance.project.service.DeliveryNoticeService;
import com.yuexunit.finance.project.service.DeliveryService;
import com.yuexunit.finance.project.service.FinanceApplicationService;
import com.yuexunit.finance.project.service.FinanceAuditService;
import com.yuexunit.finance.project.service.FinanceBulkstockColdStorageService;
import com.yuexunit.finance.project.service.FinanceBulkstockDangerousService;
import com.yuexunit.finance.project.service.FinanceBulkstockService;
import com.yuexunit.finance.project.service.FinanceContainerBillService;
import com.yuexunit.finance.project.service.FinanceContainerLogService;
import com.yuexunit.finance.project.service.FinanceContainerService;
import com.yuexunit.finance.project.service.FinanceContainerWaybillService;
import com.yuexunit.finance.project.service.FinanceContractService;
import com.yuexunit.finance.project.service.FinanceCreditBulkstockService;
import com.yuexunit.finance.project.service.FinanceCreditContainerBulkstockService;
import com.yuexunit.finance.project.service.FinanceCreditContainerService;
import com.yuexunit.finance.project.service.FinanceCreditReplenishContainerService;
import com.yuexunit.finance.project.service.FinanceCreditReplenishService;
import com.yuexunit.finance.project.service.FinanceCreditService;
import com.yuexunit.finance.project.service.FinanceEvaluateService;
import com.yuexunit.finance.project.service.FinanceEvidentiaryCategoryService;
import com.yuexunit.finance.project.service.FinanceEvidentiaryService;
import com.yuexunit.finance.project.service.FinanceMaterialService;
import com.yuexunit.finance.project.service.FinanceMoneyStatementService;
import com.yuexunit.finance.project.service.FinanceProcessDetailService;
import com.yuexunit.finance.project.service.FinanceProcessService;
import com.yuexunit.finance.project.service.FinanceProductExpenseService;
import com.yuexunit.finance.project.service.FinanceReturnBulkstockService;
import com.yuexunit.finance.project.service.FinanceReturnService;
import com.yuexunit.finance.project.service.InsuranceService;
import com.yuexunit.finance.project.service.InterestDelayApplicationService;
import com.yuexunit.finance.project.service.LoanNoticeService;
import com.yuexunit.finance.project.service.PickupApplicationService;
import com.yuexunit.finance.project.service.PickupBulkstockService;
import com.yuexunit.finance.project.service.PickupDelayApplicationService;
import com.yuexunit.finance.project.service.PickupInventoryBulstockService;
import com.yuexunit.finance.project.service.PickupInventoryService;
import com.yuexunit.finance.project.service.ReceivablesService;
import com.yuexunit.finance.project.service.RecieveNoticeInventoryService;
import com.yuexunit.finance.project.service.RecieveNoticeService;
import com.yuexunit.finance.project.service.SupervisionConfirmationService;
import com.yuexunit.finance.project.service.SupervisionContractService;
import com.yuexunit.finance.project.service.SupervisionEndallService;
import com.yuexunit.finance.project.service.SupervisionNoticeService;
import com.yuexunit.finance.project.service.TallyingService;
import com.yuexunit.finance.project.service.TransportNoticeService;
import com.yuexunit.finance.project.service.WarningSchemeResultService;
import com.yuexunit.finance.system.service.UserCardInfoService;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.util.DateUtil;

/**
 * @ClassName: FinanceBaseAction
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author chenxy
 * @date 2015年10月24日 下午5:54:00
 */
public class FinanceBaseAction {

	// 企业信息
	protected EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);

	// 大宗商品
	protected BulkstockInfoService bulkstockInfoService = ComponentFactory.loadClass(BulkstockInfoService.class);

	// 产品费用
	protected FinanceProductExpenseService financeProductExpenseService = ComponentFactory.loadClass(FinanceProductExpenseService.class);

	// 融资信息
	protected FinanceApplicationService financeApplicationService = ComponentFactory.loadClass(FinanceApplicationService.class);

	protected FinanceBulkstockService financeBulkstockService = ComponentFactory.loadClass(FinanceBulkstockService.class);

	protected FinanceEvidentiaryCategoryService financeEvidentiaryCategoryService = ComponentFactory.loadClass(FinanceEvidentiaryCategoryService.class);

	protected FinanceEvidentiaryService financeEvidentiaryService = ComponentFactory.loadClass(FinanceEvidentiaryService.class);

	protected FinanceBulkstockColdStorageService financeBulkstockColdStorageService = ComponentFactory.loadClass(FinanceBulkstockColdStorageService.class);

	protected FinanceBulkstockDangerousService financeBulkstockDangerousService = ComponentFactory.loadClass(FinanceBulkstockDangerousService.class);

	protected FinanceContainerBillService financeContainerBillService = ComponentFactory.loadClass(FinanceContainerBillService.class);

	protected FinanceContainerService financeContainerService = ComponentFactory.loadClass(FinanceContainerService.class);

	protected FinanceContainerWaybillService financeContainerWaybillService = ComponentFactory.loadClass(FinanceContainerWaybillService.class);

	protected FinanceMaterialService financeMaterialService = ComponentFactory.loadClass(FinanceMaterialService.class);

	protected FinanceAuditService financeAuditService = ComponentFactory.loadClass(FinanceAuditService.class);

	// 合同信息
	protected FinanceContractService financeContractService = ComponentFactory.loadClass(FinanceContractService.class);

	protected SupervisionContractService supervisionContractService = ComponentFactory.loadClass(SupervisionContractService.class);

	// 融资动态
	protected FinanceProcessService financeProcessService = ComponentFactory.loadClass(FinanceProcessService.class);

	protected FinanceProcessDetailService financeProcessDetailService = ComponentFactory.loadClass(FinanceProcessDetailService.class);

	// 提货信息
	protected PickupApplicationService pickupApplicationService = ComponentFactory.loadClass(PickupApplicationService.class);

	protected PickupInventoryService pickupInventoryService = ComponentFactory.loadClass(PickupInventoryService.class);

	protected PickupInventoryBulstockService pickupInventoryBulstockService = ComponentFactory.loadClass(PickupInventoryBulstockService.class);

	protected PickupBulkstockService pickupBulkstockService = ComponentFactory.loadClass(PickupBulkstockService.class);

	// 货箱信息
	protected ContainerInventoryService containerInventoryService = ComponentFactory.loadClass(ContainerInventoryService.class);

	protected ContainerBulkstockService containerBulkstockService = ComponentFactory.loadClass(ContainerBulkstockService.class);

	protected ContainerInventoryHistoryService containerInventoryHistoryService = ComponentFactory.loadClass(ContainerInventoryHistoryService.class);

	protected ContainerBulkstockHistoryService containerBulkstockHistoryService = ComponentFactory.loadClass(ContainerBulkstockHistoryService.class);

	protected ContainerInventoryTallyService containerInventoryTallyService = ComponentFactory.loadClass(ContainerInventoryTallyService.class);

	protected ContainerInventorySignService containerInventorySignService = ComponentFactory.loadClass(ContainerInventorySignService.class);

	protected ContainerInventoryRelieveService containerInventoryRelieveService = ComponentFactory.loadClass(ContainerInventoryRelieveService.class);

	// 融资完成
	protected SupervisionEndallService supervisionEndallService = ComponentFactory.loadClass(SupervisionEndallService.class);

	protected FinanceEvaluateService financeEvaluateService = ComponentFactory.loadClass(FinanceEvaluateService.class);

	// 退货信息
	protected FinanceReturnService financeReturnService = ComponentFactory.loadClass(FinanceReturnService.class);

	protected FinanceReturnBulkstockService financeReturnBulkstockService = ComponentFactory.loadClass(FinanceReturnBulkstockService.class);

	// 通知信息
	protected SupervisionNoticeService supervisionNoticeService = ComponentFactory.loadClass(SupervisionNoticeService.class);

	protected RecieveNoticeService recieveNoticeService = ComponentFactory.loadClass(RecieveNoticeService.class);

	protected RecieveNoticeInventoryService recieveNoticeInventoryService = ComponentFactory.loadClass(RecieveNoticeInventoryService.class);

	protected TransportNoticeService transportNoticeService = ComponentFactory.loadClass(TransportNoticeService.class);

	protected DeliveryNoticeService deliveryNoticeService = ComponentFactory.loadClass(DeliveryNoticeService.class);

	// 收放款
	protected LoanNoticeService loanNoticeService = ComponentFactory.loadClass(LoanNoticeService.class);

	protected ReceivablesService receivablesService = ComponentFactory.loadClass(ReceivablesService.class);

	// 估值变动
	protected FinanceCreditService financeCreditService = ComponentFactory.loadClass(FinanceCreditService.class);

	protected FinanceCreditContainerService financeCreditContainerService = ComponentFactory.loadClass(FinanceCreditContainerService.class);

	protected FinanceCreditContainerBulkstockService financeCreditContainerBulkstockService = ComponentFactory.loadClass(FinanceCreditContainerBulkstockService.class);

	protected FinanceCreditReplenishContainerService financeCreditReplenishContainerService = ComponentFactory.loadClass(FinanceCreditReplenishContainerService.class);

	protected FinanceCreditReplenishService financeCreditReplenishService = ComponentFactory.loadClass(FinanceCreditReplenishService.class);

	protected FinanceCreditBulkstockService financeCreditBulkstockService = ComponentFactory.loadClass(FinanceCreditBulkstockService.class);

	// 理货配送
	protected TallyingService tallyingService = ComponentFactory.loadClass(TallyingService.class);

	protected SupervisionConfirmationService supervisionConfirmationService = ComponentFactory.loadClass(SupervisionConfirmationService.class);

	protected DeliveryService deliveryService = ComponentFactory.loadClass(DeliveryService.class);

	// 异常处理
	protected InterestDelayApplicationService interestDelayApplicationService = ComponentFactory.loadClass(InterestDelayApplicationService.class);

	protected PickupDelayApplicationService pickupDelayApplicationService = ComponentFactory.loadClass(PickupDelayApplicationService.class);

	protected BadassetsHandleService badassetsHandleService = ComponentFactory.loadClass(BadassetsHandleService.class);

	protected BadassetsInventoryService badassetsInventoryService = ComponentFactory.loadClass(BadassetsInventoryService.class);

	// 帐户流水
	protected FinanceMoneyStatementService financeMoneyStatementService = ComponentFactory.loadClass(FinanceMoneyStatementService.class);
	
	//其他
	
	protected BailReturnService bailReturnService = ComponentFactory.loadClass(BailReturnService.class);
	
	protected WarningSchemeResultService warningSchemeResultService = ComponentFactory.loadClass(WarningSchemeResultService.class);
	
	protected AbnormalRiskService abnormalRiskService = ComponentFactory.loadClass(AbnormalRiskService.class);
	
	protected InsuranceService insuranceService = ComponentFactory.loadClass(InsuranceService.class);
	
	protected UserCardInfoService userCardInfoService = ComponentFactory.loadClass(UserCardInfoService.class);
	
	protected FinanceContainerLogService financeContainerLogService = ComponentFactory.loadClass(FinanceContainerLogService.class);

	private static String getSupervisionBatchNumber() {
		return DateUtil.todayInt() + "";
	}

	protected Long getFinanceEnterpriseId(Long financeId) {
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		return financeEntity.getEnterpriseId();
	}

	private void processPickupContainerSupervise(ContainerInventoryEntity container) {
		// 获取换箱换货产生的箱列表
		List<ContainerInventoryEntity> inventories = containerInventoryService.inquirePickupExchangeContainerInventoryList(container.getExchangePickupId());
		for (ContainerInventoryEntity cie : inventories) {
			if (SupervisionStateEnum.ALREADY_REPORT == cie.getSupervisionState()) {
				throw new BusinessException("换货箱信息,必须全部确认收货才能进入监管");
			}
		}
		PickupApplicationEntity pickup = pickupApplicationService.inquirePickupApplication(container.getExchangePickupId());
		if (ApplicationStateEnum.AGREE == pickup.getApplicationState()) { // 允许逐步放货(放货环节如果是换货换箱的放货需要校验 放货箱的总额不允许超过换货换箱进来的总额)
			pickup.setApplicationState(ApplicationStateEnum.RECEIPT);
			pickupApplicationService.renovatePickupApplication(pickup);
		}
		// 获取换箱换货的源箱信息列表(用来填充相关的计息日期)
		List<ContainerInventoryEntity> cies = containerInventoryService.inquirePickupContainerInventoryList(container.getExchangePickupId());
		for (ContainerInventoryEntity cie : cies) {
			if (cie.getValueDate() != null) {
				container.setValueDate(cie.getValueDate());
				container.setSettlementDate(cie.getSettlementDate());
				container.setPickupableDate(cie.getPickupableDate());
				container.setPunishDate(cie.getPunishDate());
				container.setDistrainDate(cie.getDistrainDate());
				container.setHandleDate(cie.getHandleDate());
				break;
			}
		}
	}

	private void processCreditContainerSupervise(ContainerInventoryEntity container) {
		List<ContainerInventoryEntity> inventories = containerInventoryService.inquireReplenishContainerInventoryList(container.getReplenishCreditId());
		for (ContainerInventoryEntity cie : inventories) {
			if (SupervisionStateEnum.ALREADY_REPORT == cie.getSupervisionState()) {
				throw new BusinessException("补货箱信息,必须全部确认收货才能进入监管");
			}
		}
		List<ContainerInventoryEntity> cies = containerInventoryService.inquireLoanNoticeContainerInventoryList(container.getLoanNoticeId());

		for (ContainerInventoryEntity containerInventoryEntity : cies) {
			if (containerInventoryEntity.getValueDate() != null) {
				container.setValueDate(containerInventoryEntity.getValueDate());
				container.setSettlementDate(containerInventoryEntity.getSettlementDate());
				container.setPickupableDate(containerInventoryEntity.getPickupableDate());
				container.setPunishDate(containerInventoryEntity.getPunishDate());
				container.setDistrainDate(containerInventoryEntity.getDistrainDate());
				container.setHandleDate(containerInventoryEntity.getHandleDate());
				break;
			}
		}

		containerInventoryService.renovateContainerInventory(container);

		// 全部补货确认完毕
		for (ContainerInventoryEntity cie : inventories) {
			if (cie.getInventoryId().equals(container.getInventoryId())) {
				continue;
			}
			if (SupervisionStateEnum.DELIVERY_SURE == cie.getSupervisionState()) {
				return;
			}
		}
		// 全部补货确认监管
		FinanceCreditEntity credit = financeCreditService.inquireFinanceCredit(container.getReplenishCreditId());
		credit.setReplenishState(ReplenishStateEnum.FINISHED);
		financeCreditService.renovateFinanceCredit(credit);
		List<FinanceCreditReplenishContainerEntity> containers = financeCreditReplenishContainerService.inquireCreditReplenishContainerList(credit.getCreditId());
		for (FinanceCreditReplenishContainerEntity e : containers) {
			e.setReplenishState(credit.getReplenishState());
			financeCreditReplenishContainerService.renovateFinanceCreditReplenishContainer(e);
		}
	}

	protected void superviseContainerInventory(Long[] inventoryIds, boolean restore, Date superviseTallyingCreateTime) {
		ContainerInventoryEntity containerInventory = containerInventoryService.inquireContainerInventory(inventoryIds[0]);
		Long financeId = containerInventory.getFinanceId();

		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		SupervisionConfirmationEntity supervision = new SupervisionConfirmationEntity();
		supervision.setFinanceId(financeId);
		supervision.setFinanceNumber(financeEntity.getFinanceNumber());
		supervision.setSupervisionAuthenticatId(FinanceSessionContext.getAccountId());
		supervision.setSupervisionAuthenticator(FinanceSessionContext.getAccountFullName());
		supervision.setSupervisionBatchNumber(getSupervisionBatchNumber());
		supervision.setSupervisionConfirmationDateTime(DateUtil.now());
		Long confirmationId = supervisionConfirmationService.createSupervisionConfirmation(supervision);

		List<ContainerInventoryEntity> inventories = containerInventoryService.inquireContainerInventoryList(inventoryIds);
		for (ContainerInventoryEntity inventory : inventories) {
			if (superviseTallyingCreateTime != null) {
				inventory.setSuperviseTallyingCreateTime(superviseTallyingCreateTime);
			}
			
//			ContainerInventoryEntity cie = containerInventoryService.inquireContainerInventory(inventory.getWaybillNumber(), inventory.getCaseNumber());
//			if (cie != null) {
//				throw new BusinessException(inventory.getWaybillNumber() + "[" + inventory.getCaseNumber() +"]提交的箱货信息已存在理货信息");
//			}
			
			if (!restore) {
				if (SupervisionStateEnum.DELIVERY_SURE != inventory.getSupervisionState()) {
					throw new BusinessException("货箱" + inventory.getCaseNumber() + "不在确认收货状态,不允许监管");
				}
			}
			if (inventory.validateAbnormal()) { // 异常不进行监管
				continue;
			}
			if (inventory.getConfirmationId() == null) {
				inventory.setConfirmationId(confirmationId);
			}
			if (BulkstockSourceEnum.CREDIT == inventory.getContainerSource()) { // 补货箱信息，必须全部确认收货后，才能确认监管，融资价格要重新计算,确认监管后会被提货
				processCreditContainerSupervise(inventory);
			} else if (BulkstockSourceEnum.PICKUP == inventory.getContainerSource()) { // 换货箱信息，必须全部确认收货后,才开始确认监管,全部监管后才允许放货
				processPickupContainerSupervise(inventory);
			}
			inventory.setSupervisionState(SupervisionStateEnum.ALREADY_SUPERVISE);
			
			if (ProductTypeEnum.PURCHASING == financeEntity.getProductType() && financeEntity.getSettlementMethod() != null && 2 == financeEntity.getSettlementMethod()) {
				List<LoanNoticeEntity> ls = loanNoticeService.inquireLoanNoticeList(financeEntity.getFinanceId());
				if (ls != null && ls.size() > 0) {
					inventory.setLoanNoticeId(ls.get(ls.size() - 1).getLoanNoticeId());
				}
			}
			
			containerInventoryService.renovateContainerInventory(inventory);
			
			FinanceContainerLogEntity fcle = new FinanceContainerLogEntity();
			fcle.setInventoryId(inventory.getInventoryId());
			fcle.setOperator(FinanceSessionContext.getAccountFullName());
			fcle.setRemark("监管确认");
			financeContainerLogService.createFinanceContainerLog(fcle);
		}
		financeBulkstockService.calculateSupervisionFinanceBulkstock(financeId);
		financeBulkstockService.calculateIncustodyFinanceBulkstock(financeId);
		financeBulkstockService.calculateAbnormalFinanceBulkstock(financeId);

		// 项目状态更新
		if (financeEntity.getFinanceState() == FinanceStateEnum.INSPECTIONED) {
			FinanceContainerEntity fce = financeContainerService.inquireFinanceContainer(financeId);
			if (fce == null) {
				throw new BusinessException("请填写订舱箱信息！");
			}
			List<ContainerInventoryEntity> cies = containerInventoryService.inquireUnSupervisionInventoryList(financeId);
			if (fce.getCaseQuantity().equals(cies.size())) {
				if ((ProductTypeEnum.PURCHASING == financeEntity.getProductType() || ProductTypeEnum.PURCHASING_STORAGE == financeEntity.getProductType()) && financeEntity.getSettlementMethod() != null && 2 == financeEntity.getSettlementMethod()) {
					List<ContainerInventoryEntity> inventories1 = containerInventoryService.inquireSupervisionFinanceAmountList(financeEntity.getFinanceId());
					BigDecimal fa = BigDecimal.ZERO;
					Date valueDate = DateUtil.thatDay(new Date()); // 当天开始计息
					Date settlementDate = DateUtils.addDateField(valueDate, Calendar.DATE, -1); // 已结算日期
					// 计算货箱的 可提日期点/罚息日期点/赎货日期点/处置日期点
					Integer advanceTimeLimit = financeEntity.getAdvanceTimeLimit(); // 提前违约期限
					Date pickupableDate = DateUtils.addDateField(valueDate, Calendar.DATE, advanceTimeLimit == null? 0 : advanceTimeLimit); // 可提开始日期-当天可提

					Integer loanTimeLimit = financeEntity.getLoanTimeLimit(); // 借款期限
					Date punishDate = DateUtils.addDateField(valueDate, Calendar.DATE, loanTimeLimit); // 罚息开始日期-当天开始罚息

					Date distrainDate = DateUtils.addDateField(punishDate, Calendar.DATE, 0);

					Date handleDate = DateUtils.addDateField(distrainDate, Calendar.DATE, 0);
					for (ContainerInventoryEntity cie : inventories1) {
						List<ContainerBulkstockEntity> cbes = containerBulkstockService.inquireContainerBulkstockList(cie.getInventoryId());
						for (ContainerBulkstockEntity cbe : cbes) {
							fa = fa.add(cbe.getValuationFinanceAmount());
						}
						cie.setSettlementDate(DateUtil.now());
						cie.setValueDate(valueDate);
						cie.setSettlementDate(settlementDate);
						cie.setPickupableDate(pickupableDate);
						cie.setPunishDate(punishDate);
						cie.setDistrainDate(distrainDate);
						cie.setHandleDate(handleDate);
						containerInventoryService.updateContainerInventory(cie);
					}
					ContainerInventoryEntity last = inventories1.get(inventories1.size() - 1);
					last.setAdjustment(financeEntity.getFinanceAmount().subtract(fa));
					containerInventoryService.updateContainerInventory(last);
				} else {
					financeEntity.setFinanceState(FinanceStateEnum.WAIT_PROTOCOL);
				}
			}
		}
		
		financeEntity.setSupervisionCreateDatetime(null);
		financeEntity.setLoanApplicationCreateDatetime(DateUtil.now());
		financeApplicationService.renovateFinanceApplication(financeEntity);

		// 项目动态
		FinanceProcessEntity processEntity = FinanceProcessCastor.fromFinanceSupervisionProcess(supervision);
		if (!LongUtils.isPrimaryKey(processEntity.getProcessId())) {
			financeProcessService.createFinanceProcess(processEntity);
		} else {
			financeProcessService.renovateFinanceProcess(processEntity);
		}
		processEntity.getCurrentDetail().setProcessId(processEntity.getProcessId());
		financeProcessDetailService.createFinanceProcessDetail(processEntity.getCurrentDetail());
	}

	@Deprecated
	protected InterestEstimate interestEstimationFinanceInventory(Long financeId, List<ContainerInventoryEntity> inventories, String cutoffDate) {
		InterestEstimate interestEstimate = new InterestEstimate();
		// 获取融资金额
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		// 获取融资货物信息
		List<FinanceBulkstockEntity> bulkstockList = financeBulkstockService.inquireFinanceBulkstockList(financeId);
		Map<Long, FinanceBulkstockEntity> bulkstocks = new HashMap<>();
		for (FinanceBulkstockEntity fbe : bulkstockList) {
			bulkstocks.put(fbe.getBulkstockId(), fbe);
		}
		for (ContainerInventoryEntity cie : inventories) {
			// 时间差
			int days = DateUtils.daysBetween(cie.getValueDate(), DateUtil.from(cutoffDate)) + 1;
			// 获取箱货信息
			List<ContainerBulkstockEntity> containerBulkstockList = containerBulkstockService.inquireContainerBulkstockList(cie.getInventoryId());
			cie.setContainerBulkstocks(containerBulkstockList);
			cie.setDateInterval(days);

			InterestContainer ic = new InterestContainer();
			ic.setInventoryId(cie.getInventoryId());
			for (ContainerBulkstockEntity cbe : containerBulkstockList) {
				InterestContainerBulkstock icb = new InterestContainerBulkstock();
				FinanceBulkstockEntity fbe = bulkstocks.get(cbe.getBulkstockId());
				BulkstockInfoEntity bulkstockInfo = bulkstockInfoService.inquireBulkstockInfo(fbe.getBulkstockInfoId());
				Long productId = finance.getProductId();
				Long bulkstockCategoryId = bulkstockInfo.getBulkstockCategoryId();
				Long bulkstockInfoId = bulkstockInfo.getBulkstockInfoId();
				FinanceProductExpenseEntity expense = null;
				// 取最长天数日息计算(TODO 可能需要改成阶梯日息计算)
				if (finance.getLoanTimeLimit() >= days) {
					expense = financeProductExpenseService.inquireFinanceProductExpense(productId, bulkstockCategoryId, bulkstockInfoId, days, ExpenseTypeEnum.AHEAD);
				} else {
					expense = financeProductExpenseService.inquireFinanceProductExpense(productId, bulkstockCategoryId, bulkstockInfoId, days - finance.getLoanTimeLimit(), ExpenseTypeEnum.DELAY);
				}

				BigDecimal interest = finance.getAuditInterest();
				if (expense != null) {
					interest = expense.getAmount();
				}
				// 计算本息比例
				BigDecimal proportion = finance.getInterest();
				if (LoanMethodEnum.DAY_LOAN == finance.getLoanMethod()) { // 按日计息
					proportion = interest.multiply(new BigDecimal(days));
				}
				proportion = proportion.divide(FinanceConstant.HUNDRED, 10, BigDecimal.ROUND_HALF_UP);
				BigDecimal bulkstockPrincipal = fbe.getFinancePrice().multiply(cbe.getValuationQuantity());
				BigDecimal bulkstockInterest = bulkstockPrincipal.multiply(proportion);
				interestEstimate.setPrincipal(interestEstimate.getPrincipal().add(bulkstockPrincipal));
				interestEstimate.setInterest(interestEstimate.getInterest().add(bulkstockInterest));

				icb.setBulkstockId(fbe.getBulkstockId());
				icb.setContainerBulkstockId(cbe.getContainerBulkstockId());
				icb.setInterest(bulkstockInterest);
				ic.getBulkstocks().add(icb);
				ic.setBulkstockValuation(ic.getBulkstockValuation().add(bulkstockPrincipal));
				cie.setBulkstockValuation(cie.getBulkstockValuation().add(bulkstockPrincipal));
			}
			// interestEstimate.getContainers().add(ic);
		}
		// 计算其他费用
		List<FinanceProductExpenseEntity> expenses = financeProductExpenseService.inquireFinanceProductExpense(finance.getProductId(), ExpenseTypeEnum.EXPENSE);
		for (FinanceProductExpenseEntity expense : expenses) {
			if (ExpenseMethodEnum.BULKSTOCK == expense.getExpenseMethod()) { // 按货计算
				for (ContainerInventoryEntity cie : inventories) {
					if (finance.getLoanTimeLimit() >= cie.getDateInterval() && ExpenseScopeEnum.OVERDUE == expense.getExpenseScope()) { // 是否超期
						continue;
					}
					BigDecimal valuation = BigDecimal.ZERO;
					for (ContainerBulkstockEntity cbe : cie.getContainerBulkstocks()) {
						if (expense.getBulkstockInfoId() != null) {
							if (cbe.getBulkstockId().equals(expense.getBulkstockInfoId())) {
								valuation = valuation.add(cbe.getValuationFinanceAmount());
							}
						} else {
							if (cbe.getBulkstockCategoryId().equals(expense.getBulkstockCategoryId())) {
								valuation = valuation.add(cbe.getValuationFinanceAmount());
							}
						}
					}
					if (valuation == null) {
						continue;
					}
					if (BillingMethodEnum.EXPENSE == expense.getBillingMethod()) {// 1:按单
						BigDecimal amount = expense.getAmount();
						if (expense.getProportion()) { // 百分比
							interestEstimate.getExpense().add(valuation.divide(FinanceConstant.HUNDRED, 10, BigDecimal.ROUND_HALF_UP).multiply(amount));
						} else { // 设定金额
							interestEstimate.getExpense().add(amount);
						}
					} else { // 2:按日
						BigDecimal amount = expense.getAmount().multiply(new BigDecimal(cie.getDateInterval()));
						if (expense.getProportion()) { // 百分比
							interestEstimate.getExpense().add(valuation.divide(FinanceConstant.HUNDRED, 10, BigDecimal.ROUND_HALF_UP).multiply(amount));
						} else { // 设定金额
							interestEstimate.getExpense().add(amount);
						}
					}
				}
			} else if (ExpenseMethodEnum.NATURE == expense.getExpenseMethod()) { // 按自然箱
				for (ContainerInventoryEntity cie : inventories) {
					if (finance.getLoanTimeLimit() >= cie.getDateInterval() && ExpenseScopeEnum.OVERDUE == expense.getExpenseScope()) { // 是否超期
						continue;
					}
					BigDecimal valuation = cie.getBulkstockValuation();
					if (StringUtils.isNoneBlank(expense.getModel()) && !expense.getModel().equals(cie.getModel())) {
						continue;
					}
					if (StringUtils.isNoneBlank(expense.getDimension()) && !expense.getDimension().equals(cie.getDimension())) {
						continue;
					}
					if (BillingMethodEnum.EXPENSE == expense.getBillingMethod()) {// 1:按单
						BigDecimal amount = expense.getAmount();
						if (expense.getProportion()) { // 百分比
							interestEstimate.getExpense().add(valuation.divide(FinanceConstant.HUNDRED, 10, BigDecimal.ROUND_HALF_UP).multiply(amount));
						} else { // 设定金额
							interestEstimate.getExpense().add(amount);
						}
					} else { // 2:按日
						BigDecimal amount = expense.getAmount().multiply(new BigDecimal(cie.getDateInterval()));
						if (expense.getProportion()) { // 百分比
							interestEstimate.getExpense().add(valuation.divide(FinanceConstant.HUNDRED, 10, BigDecimal.ROUND_HALF_UP).multiply(amount));
						} else { // 设定金额
							interestEstimate.getExpense().add(amount);
						}
					}
				}
			} else if (ExpenseMethodEnum.STANDARD == expense.getExpenseMethod()) { // 按标准箱
				for (ContainerInventoryEntity cie : inventories) {
					if (finance.getLoanTimeLimit() >= cie.getDateInterval() && ExpenseScopeEnum.OVERDUE == expense.getExpenseScope()) { // 是否超期
						continue;
					}
					BigDecimal valuation = cie.getBulkstockValuation().multiply(new BigDecimal(cie.getDimension()).divide(new BigDecimal(20), 10, BigDecimal.ROUND_HALF_UP));
					if (BillingMethodEnum.EXPENSE == expense.getBillingMethod()) {// 1:按单
						BigDecimal amount = expense.getAmount();
						if (expense.getProportion()) { // 百分比
							interestEstimate.getExpense().add(valuation.divide(FinanceConstant.HUNDRED, 10, BigDecimal.ROUND_HALF_UP).multiply(amount));
						} else { // 设定金额
							interestEstimate.getExpense().add(amount.multiply(new BigDecimal(cie.getDimension()).divide(new BigDecimal(20), 10, BigDecimal.ROUND_HALF_UP)));
						}
					} else { // 2:按日
						BigDecimal amount = expense.getAmount().multiply(new BigDecimal(cie.getDateInterval()));
						if (expense.getProportion()) { // 百分比
							interestEstimate.getExpense().add(valuation.divide(FinanceConstant.HUNDRED, 10, BigDecimal.ROUND_HALF_UP).multiply(amount));
						} else { // 设定金额
							interestEstimate.getExpense().add(amount.multiply(new BigDecimal(cie.getDimension()).divide(new BigDecimal(20), 10, BigDecimal.ROUND_HALF_UP)));
						}
					}
				}
			} else if (ExpenseMethodEnum.OTHER == expense.getExpenseMethod()) { // 按其他方式
				for (ContainerInventoryEntity cie : inventories) {
					if (finance.getLoanTimeLimit() >= cie.getDateInterval() && ExpenseScopeEnum.OVERDUE == expense.getExpenseScope()) { // 是否超期
						continue;
					}
					BigDecimal valuation = cie.getBulkstockValuation();
					if (BillingMethodEnum.EXPENSE == expense.getBillingMethod()) {// 1:按单
						BigDecimal amount = expense.getAmount();
						if (expense.getProportion()) { // 百分比
							interestEstimate.getExpense().add(valuation.divide(FinanceConstant.HUNDRED, 10, BigDecimal.ROUND_HALF_UP).multiply(amount));
						} else { // 设定金额
							interestEstimate.getExpense().add(amount);
						}
					} else { // 2:按日
						BigDecimal amount = expense.getAmount().multiply(new BigDecimal(cie.getDateInterval()));
						if (expense.getProportion()) { // 百分比
							interestEstimate.getExpense().add(valuation.divide(FinanceConstant.HUNDRED, 10, BigDecimal.ROUND_HALF_UP).multiply(amount));
						} else { // 设定金额
							interestEstimate.getExpense().add(amount);
						}
					}
				}
			}
		}
		interestEstimate.setPrincipal(interestEstimate.getPrincipal().setScale(2, BigDecimal.ROUND_HALF_UP));
		interestEstimate.setInterest(interestEstimate.getInterest().setScale(2, BigDecimal.ROUND_HALF_UP));
		interestEstimate.setSummation(interestEstimate.getPrincipal().add(interestEstimate.getInterest()).add(interestEstimate.getExpense()).setScale(2, BigDecimal.ROUND_HALF_UP));
		return interestEstimate;
	}

	protected void confirmAuthenticat(AuthenticatEntity authenticat) {
		if (AuthenticatStateEnum.CONFIRMED == authenticat.getAuthenticatState()) {
			throw new BusinessException("已经确认");
		}
		authenticat.setAuthenticatId(FinanceSessionContext.getAccountId());
		authenticat.setAuthenticator(FinanceSessionContext.getAccountFullName());
		authenticat.setAuthenticatDateTime(DateUtil.now());
		authenticat.setAuthenticatState(AuthenticatStateEnum.CONFIRMED);
	}

	protected void confirmAuthenticat(AuthenticatEntity authenticat, boolean direct) {
		authenticat.setReportor(FinanceSessionContext.getAccountFullName());
		authenticat.setAuthenticatState(AuthenticatStateEnum.UNCONFIRM);
		if (direct) {
			confirmAuthenticat(authenticat);
		}
	}

}
